//
// This file is part of the aMule Project.
//
// Copyright (c) 2004-2006 Angel Vidal (Kry) ( kry@amule.org )
// Copyright (c) 2004-2006 aMule Team ( admin@amule.org / http://www.amule.org )
// Copyright (c) 2003 Barry Dunne (http://www.emule-project.net)
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
//

// Note To Mods //
/*
 Please do not change anything here and release it..
 There is going to be a new forum created just for the Kademlia side of the client..
 If you feel there is an error or a way to improve something, please
 post it in the forum first and let us look at it.. If it is a real improvement,
 it will be added to the offical client.. Changing something without knowing
 what all it does can cause great harm to the network if released in mass form..
 Any mod that changes anything within the Kademlia side will not be allowed to advertise
 there client on the eMule forum..
 */


#include <malloc.h>
#include "Kademlia.h"
#include "Defines.h"
#include "Prefs.h"
#include "SearchManager.h"
#include "KademliaUDPListener.h"
#include <RoutingZone.h>
#include "Contact.h"
#include "OPCodes.h"
#include "UInt128.h"

#include "kademliamain.h"

extern "C" {
#include "KadClog.h"
#include <netinet/in.h>
}

#include <cstdio>
#include <cstring>
#include <iostream>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define time(NULL)  KadClog_get_current_dvn_time()

////////////////////////////////////////
using namespace std;
////////////////////////////////////////

//This is the initialization of the static variables inside of the class
//[dfk] moved all the static varibles into a memory structure.
//      then swap everything in when the node is used by DVN
/*
 CKademlia	*CKademlia::instance = NULL;
 EventMap	CKademlia::m_events;
 time_t		CKademlia::m_nextSearchJumpStart;
 time_t		CKademlia::m_nextSelfLookup;
 time_t		CKademlia::m_statusUpdate;
 time_t		CKademlia::m_bigTimer;
 time_t		CKademlia::m_nextFirewallCheck;
 time_t		CKademlia::m_nextFindBuddy;
 time_t		CKademlia::m_bootstrap;
 bool		CKademlia::m_running = false;
 UDPIO		*CKademlia::myUDP = NULL;
 unsigned long int CKademlia::bytes_sent = 0;
 int 		CKademlia::packets_sent = 0;
 */

///////////////////////////////////////////////////
//
// The init function called by DVN
// Contains the code from the main() routine
//
///////////////////////////////////////////////////
void kademliaMain_init(
                       char* addr, 
                       char* port,
		       int bootstrap_needed,
		       uint32_t bootstrap_ip,
		       uint16_t bootstrap_port,
                       void** curNodeMem     /* The address of the pointer that DVN keeps for each node */
                       ){
	
	/* [dfk] 
	There are 2 ways to do things.
	1) Spawn a thread that will process messages exactly the same way that the main() routine used to do.
	2) We do all the initialization of the main routine here, and instead of an infinite loop, 
	we call the appropriate functions when we receive an event or a message.  So we change from a 
	polling mechanism to an event based system

	[dfk]  We are using approach (2)
	
	*/
	struct kad_node_mem_t* curNode = NULL;
	struct timeval zero_time;
	//SDRIlog(cbif, 1, "Initializing a new node...\n"); 

	KadC_logt(GENERAL_PRINT, "Starting new node: %s\n", addr);
	//For DVN, we assume that the simulation always starts at time = 0
	// TODO:  We can set this to the actual simulation start time
	memset(&zero_time, 0x0, sizeof(struct timeval));
	KadClog_set_start_dvn_time(zero_time);

	
	/* allocates memory for the current node */
	curNode = (struct kad_node_mem_t*) malloc(sizeof(struct kad_node_mem_t));
	
	/*initializes everything to 0x00*/
	memset(curNode, 0x00,sizeof(struct kad_node_mem_t)); 
	
	//[dfk] initializes the variables
	*curNodeMem = curNode;
	CKademlia *kadNode = new CKademlia();
	kadNode->mySearchMan = new CSearchManager();
	kadNode->mySearchMan->parentInstance = kadNode;
	kadNode->m_running = false;
	kadNode->myUDP = NULL;

	/*The node always start with 2 (random ID).  TODO:  Need to get this passed in from the "command line"*/
	kadNode->start(addr, port, 2);
	
	CUInt128 test;
	CPrefs *myprefs;
	myprefs = kadNode->getPrefs();
	
	test.setValue(myprefs->getKadID());

	KadC_logt(
		  SPECIAL_PRINT,
		  "Starting Kad network with hash: %X%X%X%X\n",
		  test.get32BitChunk(0),
		  test.get32BitChunk(1),
		  test.get32BitChunk(2),
		  test.get32BitChunk(3));
	KadC_logt(STARTUP_PRINT, "New node ip address: %s:%s - hash: %X%X%X%X\n",
		                addr,
		                port,
				test.get32BitChunk(0),
				test.get32BitChunk(1),
				test.get32BitChunk(2),
				test.get32BitChunk(3)); 

	/*If it's a 'create_node_via' then we bootstrap off of someone
	  void CKademlia::bootstrap(uint32 ip, uint16 port)*/
	/*[TODO]CKademlia::bootstrap(domain2hip(argv[2]), atoi(argv[3]));*/
	if(bootstrap_needed == 1)
	  kadNode->bootstrap(bootstrap_ip, bootstrap_port);
	
	//dfk: Removed the following that seemed to be associated with searches
	//     Was getting in the way
	//CUInt128 searchnode;
	//CUInt128 tempid;
	//CUInt128 search_ID;
	//CUInt128 add_ID;
	//CUInt128 distance(CKademlia::getPrefs()->getKadID());
	//distance.XOR(searchnode);

  curNode->instance = reinterpret_cast<void *>(kadNode);
	return;
}

/////////////////////////////////////////////////
//
// Once we queued a packet from the lower layer, we process it the way the main() routine used to do it
// The alternative is to spawn a thread to process the packet with 
//
/////////////////////////////////////////////////
void kademliaMain_onrecv(
			 void* modmem,			 		    
			 unsigned char* inBuf, 
			 int inBufLen, 
			 unsigned long int src_ip,
			 unsigned int src_port
			 ){
  CKademlia *curNode
    = reinterpret_cast<CKademlia *>(
        reinterpret_cast<struct kad_node_mem_t *>(modmem)->instance);
  udp_recv_packet( curNode->myUDP,
		   inBuf,
		   inBufLen,
		   src_ip,
		   src_port);
	return;
}

int kademliaMain_onProcess(
			   void* modmem,
			   time_t curTime
			 ){
  int sleep_delay = 0;
  CKademlia *curNode
    = reinterpret_cast<CKademlia *>(
        reinterpret_cast<struct kad_node_mem_t *>(modmem)->instance);
  bool indata = false;
  do {
    indata = curNode->getPacket();
  }while(indata == true);

  curNode->process();

  sleep_delay = curNode->sleep_until;

  return sleep_delay;
}

void kademliaMain_onDestroy(void *modmem, time_t curTime) {
  CKademlia *curNode
    = reinterpret_cast<CKademlia *>(
      reinterpret_cast<struct kad_node_mem_t *>(modmem)->instance);
  delete curNode;
}
